#include <errno.h>
#include <pthread.h>
#include "MessageDeliveryService.h"
#include "DBConnection.h"
#include "../Komunikacja/Log.h"
#include "../Komunikacja/Response.h"

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

MessageDeliveryService::MessageDeliveryService()
{
}

MessageDeliveryService::~MessageDeliveryService()
{
}

int MessageDeliveryService::messageListener(Message * msg){
	//TODO Pluto: wpisuj tutaj wywolania bazy danych i do logiki biznesowej.
	//TODO Liso: trzeba zajac sie obsluga res (resulta).
	DBConnection * db = DBConnection::GetInstance();
	Response * resp = NULL;
	switch (msg->type) {
		case Message::TYPE_GET:
			debug1("Handle GET message");
				pthread_mutex_lock( &mutex );
			resp = db->takeFromDB(msg);
			resp->reserved = msg->reserved;
			MsgReply(msg->reserved, EOK, resp, sizeof(Response));
				pthread_mutex_unlock( &mutex );
			break;
		case Message::TYPE_ADD:
			debug1("Handle ADD message");
				pthread_mutex_lock( &mutex );
			resp = db->addToDB(msg);
			resp->reserved = msg->reserved;
			MsgReply(msg->reserved, EOK, resp, sizeof(Response));
				pthread_mutex_unlock( &mutex );
			break;
		case Message::TYPE_GET_INFO:
			debug1("Handle GET_INFO message");
				pthread_mutex_lock( &mutex );
			resp = db->getInfoFromDB(msg);
			resp->reserved = msg->reserved;
			MsgReply(msg->reserved, EOK, resp, sizeof(Response));
				pthread_mutex_unlock( &mutex );
			break;
		case Message::TYPE_NEW:
			debug1("Handle NEW message");
				pthread_mutex_lock( &mutex );
			resp = db->setRelationInDB(msg);
			resp->reserved = msg->reserved;
			MsgReply(msg->reserved, EOK, resp, sizeof(Response));
				pthread_mutex_unlock( &mutex );
			break;
		case Message::TYPE_DELETE:
			debug1("Handle DELETE message");
				pthread_mutex_lock( &mutex );
			resp = db->dropRelationInDB(msg);
			resp->reserved = msg->reserved;
			MsgReply(msg->reserved, EOK, resp, sizeof(Response));
				pthread_mutex_unlock( &mutex );
			break;
		default:
			debug1("Error during message delivery - unknown message type");
			MsgReply(msg->reserved, -1, NULL, 0);
			break;
	}
	if(resp != NULL){
		delete resp;
	}
	return 0;
}
